package com.sitech.ibnms.util.upload;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHThread extends Thread implements RomoteController {
	private String host;
	private int port;
	private String user;
	private String password;
	private boolean autorized = false;
	private String keywords = null;
	// 存放命令执行结果
	private StringBuffer result = new StringBuffer();

	private Session session;
	private Channel channel;

	public SSHThread(String host, int port, String user, String password) {
		this.host = host;
		this.port = port;
		this.user = user;
		this.password = password;
	}
	
	public void run() {
		super.run();
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		try {
			channel.disconnect();
			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 执行命令
	 */
	public void doCommand(String command) {
		try {
			this.result = new StringBuffer();
			channel = session.openChannel("exec");
			if (command != null && !command.endsWith("\n")) {
				command = command + "\n";
			}
			((ChannelExec) channel).setCommand(command);
			channel.connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getResult() {
		InputStream is = null;
		InputStream extIs = null;
		
		byte[] tmp = new byte[1024];
		long timeout = 5000;
		long wait=0;
		
		try {
			is = channel.getInputStream();
			extIs = channel.getExtInputStream();
			
			while (is != null && timeout > wait) {
				while (is.available() > 0) {
					int i = is.read(tmp, 0, 1024);
					if (i <= 0)
						break;
					this.result.append(new String(tmp, 0, i));
				}

				while (extIs.available() > 0) {
					int i = extIs.read(tmp, 0, 1024);
					if (i <= 0)
						break;
					this.result.append(new String(tmp, 0, i));
				}

				if (channel.isClosed()||channel.isEOF()) {
					System.out.println("exit-status: " + channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
					wait += 1000;
					System.out.println("wait 1000");
				} catch (Exception ee) {
				}
			}// end while
		} catch (Exception e) {
			e.printStackTrace();
			this.result = new StringBuffer();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if(extIs != null){
					extIs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return this.result.toString();
	}
	
	/**
	 * 初始化SSH连接
	 */
	public void initial() {
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(user, host, port);
			session.setPassword(this.password);
			
			session.setConfig("StrictHostKeyChecking", "no");
			session.connect(30000);
			this.autorized = true;
		} catch (Exception e) {
			System.out.println("ssh创建session失败");
			return;
		}
	}

	public boolean isAuthorized() {
		return this.autorized;
	}

	public boolean isExistDir(String dir) {
		boolean success = true;
		this.doCommand("cd " + dir + "\n");
		try {
			InputStream in = channel.getInputStream();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					result.append((char) nextChar);
				}
				if (channel.isClosed()) {
					if (channel.getExitStatus() != 0) {
						success = false;
					}
					in.close();
					break;
				}
				try {
					Thread.sleep(500);
				} catch (Exception ee) {
					ee.printStackTrace();
				}
			}
		} catch (Exception e) {
			this.result = new StringBuffer();
			e.printStackTrace();
		}
		return success;
	}

	public boolean isRunning(String keywords, String username) {
		this.keywords = keywords;
		String command = "ps -ef | grep " + this.keywords;
		if (username != null && !"".equals(username)) {
			command += " | grep " + username;
		}
		command = command + " | grep -v grep";
		this.doCommand(command);
		String result = this.getResult();
		if (result != null && result.indexOf(this.keywords) != -1) {
			return true;
		} else {
			return false;
		}
	}
	
	public boolean isRunning(String keywords) {
		this.keywords = keywords;
		this.doCommand("ps -ef | grep " + this.keywords);
		String result = this.getResult();
		result = result.replaceAll("grep " + this.keywords, " ");
		if (result != null && result.indexOf(this.keywords) != -1) {
			return true;
		} else {
			return false;
		}
	}
	
	public boolean isUsed(int port) {
		this.doCommand("netstat -an | grep -v TIME_WAIT | awk '{print $4}' | grep " + port + "");
		String result = this.getResult();
		
		if (result != null && result.indexOf("" + port) >= 0) {
			return true;
		}
		
		return false;
	}

	public boolean getResultAsString(String targetString) {
		try {
			InputStream in = channel.getInputStream();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					result.append((char) nextChar);
					if (this.result.toString().indexOf(targetString) != -1) {
						return true;
					}
				}
				if (channel.isClosed() || channel.isEOF()) {
					in.close();
					break;
				}
				try {
					Thread.sleep(500);
				} catch (Exception ee) {
					ee.printStackTrace();
					return false;
				}
			}
		} catch (Exception e) {
			this.result = new StringBuffer();
			e.printStackTrace();
			return false;
		}
		if (this.result.toString().indexOf(targetString) != -1) {
			return true;
		} else {
			return false;
		}
	}

	public int childCountOfDir(String dir) {
		int count = 0;
		try {
			if (this.isExistDir(dir)) {
				this.doCommand("cd " + dir + ";ls -l | wc -l");
				String result = this.getResult();
				count = Integer.valueOf(result.trim()).intValue() - 1;
			} else {
				count = -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			count = -1;
		}
		return count;
	}

	public boolean createDir(String dir) {
		boolean isExist = false;
		if (dir != null && !dir.trim().equals("") && this.isExistDir(dir)) {
			isExist = true;
		}
		// 逐层分析目录，如果没有则创建.
		if (dir != null && !dir.trim().equals("") && !this.isExistDir(dir)) {
			String[] split_dir = dir.split("/");
			for (int i = 0; i < split_dir.length; i++) {
				String path = "";
				for (int j = 0; j <= i; j++) {
					if (split_dir[j] != null && !split_dir[j].equals("")) {
						path += "/" + split_dir[j];
					}
				}

				if (path != null && !path.equals("")) {
					if (!this.isExistDir(path)) {
						this.doCommand("mkdir " + path);
						this.getResult();
						System.out.println("creat path=" + path);
					}
					if (!this.isExistDir(path)) {
						System.out.println("cat not creat path=" + path);
						return false;
					}
				}
			}
			if (this.isExistDir(dir)) {
				isExist = true;
			}
		}
		return isExist;
	}

	public static void main(String[] args) {
		SSHThread ss = new SSHThread("172.21.0.131", 22, "bnmsapp2", "bnmsapp2");
		ss.initial();
		ss.doCommand("cd /bnmsapp2/lianlian/masteragent/bin/; ksh startagent.sh");
		String startAgentMsg = ss.getResult();
		System.out.println(startAgentMsg);
		ss.close();
	}
}
